const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");

const mount = require("mount-routes");

const app = express();
const resExtract = require("./modules/resextract");
const admin_passport = require("./modules/passport");

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));

app.use(express.json());
// parse application/x-www-form-urlencoded
//fasle支持字符串 true支持qs查询 任意类型
app.use(express.urlencoded({ extended: true }));

app.use(cookieParser());

//初始化数据库模块
var database = require("./modules/database");
database.initialize(app, function (err) {
  if (err) {
    console.error("连接数据库失败 %s", err);
  }
});

app.use(express.static(path.join(__dirname, "public")));
//访问图片地址
app.use("/tmp_uploads", express.static("tmp_uploads"));
app.use("/uploads/goodspics", express.static("uploads/goodspics"));
//统一响应
app.use(resExtract);

//初始化 passport 策略
admin_passport.initialize();
app.use("/api/private/v1/login", admin_passport.login);
app.use("/api/private/v1/*", admin_passport.tokenAuth);

// app.use(function(req, res, next) {
//   res.header('Access-Control-Allow-Origin', '*'); // 允许任何源
//   res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // 允许的HTTP方法
//   // res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, refresh_token, appserverid, systemtype'); // 允许的HTTP请求头
//   res.header('Access-Control-Allow-Headers', '*'); // 允许的HTTP请求头
//   next();
// });

mount(app, path.join(process.cwd(), "routes"), true);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
